﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace CPPEI.ETL.TaskAgent.Threads
{
    public static class ScanThread
    {
        private static bool s_isStarted = false;
        private static bool s_isRunning = false;

        private static Thread s_thread;
        private static long s_lastTicks = 0;
        private static long s_interval = TimeSpan.FromSeconds(60).Ticks;

        private static EventWaitHandle s_waitHandle;

        public static void Start()
        {
            if (s_isStarted)
            {
                return;
            }

            Logger.DebugToTag(Library.LogTAG, "扫描任务的线程启动");
            s_waitHandle = new EventWaitHandle(false, EventResetMode.ManualReset);
            s_isRunning = true;
            s_isStarted = true;
            s_thread = new Thread(Running);
            s_thread.Start();

        }

        public static void Stop()
        {
            if (s_isRunning)
            {
                s_isRunning = false;
                s_waitHandle.WaitOne();
                s_waitHandle = null;
                s_isStarted = false;
            }
            Logger.DebugToTag(Library.LogTAG, "扫描任务的线程结束");
        }

        private static void Running()
        {
            Logger.DebugToTag(Library.LogTAG, "扫描任务的线程开始运行...");
            while (s_isRunning)
            {
                long nowTicks = DateTime.Now.Ticks;
                if(nowTicks - s_lastTicks > s_interval)
                {
                    // execute
                    // 扫描文件
                    List<CPPEI.ETL.Domain.TaskProxy.TaskFile> taskFiles = CPPEI.ETL.Domain.TaskProxy.TaskProxyManager.Scan();

                    SyncTask(taskFiles);

                    s_lastTicks = DateTime.Now.Ticks;
                }
                else
                {
                    Thread.Sleep(10000);
                }
            }

            s_waitHandle.Set();
            Logger.DebugToTag(Library.LogTAG, "扫描任务的线程结束运行...");
        }

        private static void SyncTask(List<CPPEI.ETL.Domain.TaskProxy.TaskFile> taskFiles)
        {
            bool isExist = false;
            // 和已有的任务比较，去掉多余的，创建新增的
            for (int taskIndex = 0; taskIndex < Cache.TaskList.Count;)
            {
                isExist = false;
                CPPEI.ETL.Domain.TaskProxy.Task task = Cache.TaskList[taskIndex];

                for (int fileIndex = 0; fileIndex < taskFiles.Count; fileIndex++)
                {
                    CPPEI.ETL.Domain.TaskProxy.TaskFile taskFile = taskFiles[fileIndex];
                    if(task.Id == taskFile.Id)
                    {
                        isExist = true;
                        break;
                    }
                }

                if(!isExist)
                {
                    // remove task
                    Cache.TaskList.RemoveAt(taskIndex);
                    Logger.InfoToTag(Library.LogTAG, string.Format("从缓存中删除任务实例id:{0},index:{1}", task.Id, taskIndex));
                }
                else
                {
                    taskIndex++;
                }
            }


            bool needUpdate = false;
            int updateIndex = 0;
            for (int fileIndex = 0; fileIndex < taskFiles.Count; fileIndex++)
            {
                isExist = false;
                needUpdate = false;
                CPPEI.ETL.Domain.TaskProxy.TaskFile taskFile = taskFiles[fileIndex];

                for (int taskIndex = 0; taskIndex < Cache.TaskList.Count; taskIndex++)
                {
                    CPPEI.ETL.Domain.TaskProxy.Task task = Cache.TaskList[taskIndex];
                    if(taskFile.Id ==  task.Id)
                    {
                        isExist = true;
                        if(taskFile.ModifiedTime != task.ModifiedTime)
                        {
                            needUpdate = true;
                            updateIndex = taskIndex;
                        }
                        break;
                    }
                }

                if(isExist)
                {
                    if(needUpdate)
                    {
                        // recreate task object
                        CPPEI.ETL.Domain.TaskProxy.Task newTask = CPPEI.ETL.Domain.TaskProxy.TaskProxyManager.Load(taskFiles[fileIndex].Path);
                        Cache.TaskList[updateIndex] = newTask;
                        Logger.InfoToTag(Library.LogTAG, string.Format("更新了任务实例id:{0}, ModifiedTime:{1}", newTask.Id, newTask.ModifiedTime));
                    }
                }
                else
                {
                    // create task object
                    CPPEI.ETL.Domain.TaskProxy.Task newTask = CPPEI.ETL.Domain.TaskProxy.TaskProxyManager.Load(taskFiles[fileIndex].Path);
                    Cache.TaskList.Add(newTask);
                    Logger.InfoToTag(Library.LogTAG, string.Format("创建了新的任务实例id:{0}, ModifiedTime:{1}", newTask.Id, newTask.ModifiedTime));
                }
            }
        }
    }
}
